package weaver.interfaces.gangwan.action;

import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import org.apache.commons.lang3.StringUtils;
import weaver.conn.RecordSet;
import weaver.formmode.setup.ModeRightInfo;
import weaver.general.BaseBean;
import weaver.interfaces.gangwan.util.CommonUtil;
import weaver.interfaces.workflow.action.Action;
import weaver.soa.workflow.request.RequestInfo;
import weaver.workflow.request.RequestManager;

import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @version 1.0
 * @Title ecology-9
 * @Company 泛微软件
 * @CreateDate 2025/6/25
 * @Description 人员入职同步考勤机
 * @Author AdminZm
 */
public class HrmEntrySnycKqjAction implements Action {

    BaseBean baseBean = new BaseBean();
    
    @Override
    public String execute(RequestInfo requestInfo) {
        RequestManager requestManager = requestInfo.getRequestManager();
        int billId = requestManager.getBillid();
        String tableName = requestManager.getBillTableName();
        String requestId = requestInfo.getRequestid();
        baseBean.writeLog("HrmEntrySnycKqjAction start:" + requestId + "、" + billId + "、" + tableName);
        RecordSet rs = new RecordSet();
        RecordSet rs1 = new RecordSet();
        try {
            String modeId = rs.getPropValue("gangwan_zm_prop", "rytbkqjjlglb_mode_id");
            String cusId = rs.getPropValue("gangwan_zm_prop", "rytbkqjjlglb_cus_id");
            SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat sdfTime = new SimpleDateFormat("HH:mm:ss");
            String url = baseBean.getPropValue("gangwan_zm_prop", "kqj_url");
            String token = baseBean.getPropValue("gangwan_zm_prop", "kqj_token");
            String entryUrl = url + "api/person/add?access_token=" + token;
            String setAreaUrl = url + "/api/attAreaPerson/set?access_token=" + token;

            Gson gson = new Gson();
            Type type = new TypeToken<Map<String, Object>>() {}.getType();

            rs.executeQuery("SELECT a.xm, a.bm, b.id, a.kqjzp FROM " + tableName + "_dt1 a " +
                    " LEFT JOIN hrmresource b ON a.sfzhm = b.certificatenum AND a.rzrq = b.companystartdate " +
                    " WHERE mainid = ?", billId);
            while (rs.next()) {
                String xm = rs.getString("xm");
                String bm = rs.getString("bm");
                String pin = rs.getString("id");
                String kqjzp = rs.getString("kqjzp");
                if (StringUtils.isEmpty(xm) || StringUtils.isEmpty(bm) || StringUtils.isEmpty(pin) || StringUtils.isEmpty(kqjzp)) {
                    continue;
                }
                String dataId = null;
                try {
                    Map<String, Object> paramMap = new HashMap<>();
                    Map<String, Object> paramMap_bk = new HashMap<>();
                    rs1.executeQuery("SELECT docid,IMAGEFILEID FROM DOCIMAGEFILE WHERE docid=?", kqjzp);
                    if (rs1.next()) {
                        String imageFileId = rs1.getString("IMAGEFILEID");
                        if (StringUtils.isNotEmpty(imageFileId)) {
                            String imageBase64 = CommonUtil.imageBase64(Integer.parseInt(imageFileId));
                            paramMap.put("personPhoto", imageBase64);
                            paramMap_bk.put("personPhoto", imageFileId);
                        }
                    }
                    paramMap.put("pin", pin);
                    paramMap.put("deptCode", bm);
                    paramMap.put("name", xm);
                    paramMap_bk.put("pin", pin);
                    paramMap_bk.put("deptCode", bm);
                    paramMap_bk.put("name", xm);
                    String uuid = UUID.randomUUID() + "";
                    rs.executeUpdate("INSERT INTO uf_rytbkqjjlglb (lcqqid, lx, qqcs, formmodeid,MODEUUID,modedatacreater," +
                                    "modedatacreatertype, modedatacreatedate, modedatacreatetime) VALUES (?,?,?,?,?,?,?,?,?)",
                            requestId, "0", JSONObject.toJSONString(paramMap_bk), modeId, uuid, "1", "0", sdfDate.format(new Date()), sdfTime.format(new Date()));
                    rs.executeQuery("SELECT id FROM uf_rytbkqjjlglb WHERE MODEUUID = ?", uuid);
                    if (rs.next()) {
                        dataId = rs.getString("id");
                    }
                    String result = HttpRequest.post(entryUrl)
                            .header(Header.CONTENT_TYPE, "application/json")
                            .body(JSONObject.toJSONString(paramMap))
                            .timeout(20000)
                            .execute().body();
                    baseBean.writeLog("HrmEntrySnycKqjAction result is:" + xm + "、" + result);
                    rs.executeUpdate("UPDATE uf_rytbkqjjlglb SET jgxy = ? WHERE id = ?", result, dataId);
                    if (StringUtils.isEmpty(result)) {
                        rs.executeUpdate("UPDATE uf_rytbkqjjlglb SET jg = 1 WHERE id = ?", dataId);
                        continue;
                    }
                    Map<String, Object> resultMap = gson.fromJson(result, type);
                    Object message = resultMap.get("message");
                    if (message != null && StringUtils.equals(message.toString(), "success")) {
                        rs.executeUpdate("UPDATE uf_rytbkqjjlglb SET jg = 0 WHERE id = ?", dataId);

                        Map<String, Object> areaParamMap = new HashMap<>();
                        areaParamMap.put("pins", pin);
                        areaParamMap.put("code", "00");
                        baseBean.writeLog("HrmEntrySnycKqjAction start to set area:" + areaParamMap);
                        String areaResult = HttpRequest.post(setAreaUrl)
                                .header(Header.CONTENT_TYPE, "application/json")
                                .body(JSONObject.toJSONString(areaParamMap))
                                .timeout(20000)
                                .execute().body();
                        baseBean.writeLog("HrmEntrySnycKqjAction area areaResult is:" + xm + "、" + areaResult);
                    } else {
                        rs.executeUpdate("UPDATE uf_rytbkqjjlglb SET jg = 1 WHERE id = ?", dataId);
                    }
                } catch (Exception e) {
                    baseBean.writeLog("HrmEntrySnycKqjAction dt error:" + e);
                    rs.executeUpdate("UPDATE uf_rytbkqjjlglb SET yc = ?, jg = 1 WHERE id = ?", e.getMessage(), dataId);
                }
            }
            // 权限重构
            ModeRightInfo modeRightInfo = new ModeRightInfo();
            modeRightInfo.setNewRight(true);
            modeRightInfo.editModeDataShare(1, Integer.parseInt(modeId), Integer.parseInt(cusId));
        } catch (Exception e) {
            baseBean.writeLog("HrmEntrySnycKqjAction error:" + e);
        }
        baseBean.writeLog("HrmEntrySnycKqjAction end.");
        return Action.SUCCESS;
    }
}
